package cn.hunter.controller;

import cn.hunter.config.ProjectUrlConfig;
import cn.hunter.enums.ResultEnum;
import cn.hunter.excpetion.SellException;
import cn.hunter.utils.wechat.CheckUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

/**
 * @ClassName WechatController
 * @Description 微信授权接口
 * @Author 123
 * @Date 2018/5/2 21:09
 **/
@Slf4j
@Controller
@RequestMapping("/wechat")
public class WechatController {

    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private WxMpService wxOpenService;
    @Autowired
    private ProjectUrlConfig projectUrlConfig;

    /**
     * 功能描述: 【买家端】微信授权
     * <p>
     * 作者: luohongquan
     * 日期: 2018/5/3 0003 15:12
     */
    @GetMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl) {
        String url = projectUrlConfig.getWechatMpAuthorize() + "/sell/wechat/userInfo";
        // String redirectURL = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAUTH2_SCOPE_USER_INFO, URLEncoder.encode(returnUrl));
        String redirectURL = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAUTH2_SCOPE_USER_INFO, URLEncoder.encode(returnUrl));
        log.info("【微信网页授权】获取code，redirectURL={}", redirectURL);
        return "redirect:" + redirectURL;
    }

    /**
     * 功能描述: 【买家端】获取openId
     * <p>
     * 作者: luohongquan
     * 日期: 2018/5/3 0003 15:12
     */
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code,
                             @RequestParam("state") String returnUrl) {
        log.info("【微信网页授权】code={}", code);
        log.info("【微信网页授权】state={}", returnUrl);
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            log.error("【微信网页授权】{}", e);
            throw new SellException(ResultEnum.WECHAT_MP_ERROR.getCode(), e.getError().getErrorMsg());
        }

        String openId = wxMpOAuth2AccessToken.getOpenId();
        log.info("【微信网页授权】openId={}", openId);
        return "redirect:" + returnUrl + "?openid=" + openId;
    }

    /**
     * 功能描述: 【卖家端后台】微信授权
     * 浏览器：http://hunterfish.ngrok.xiaomiqiu.cn/sell/wechat/qrAuthorize?returnUrl=http://www.baidu.com
     * <p>
     * 作者: luohongquan
     * 日期: 2018/5/8 0008 11:48
     */
    @GetMapping("/qrAuthorize")
    public String qrAuthorize(@RequestParam("returnUrl") String returnUrl) {
        String url = projectUrlConfig.getWechatOpenAuthorize() + "/sell/wechat/userInfo";
        String redirectURL = wxOpenService.oauth2buildAuthorizationUrl(url, WxConsts.QRCONNECT_SCOPE_SNSAPI_LOGIN, URLEncoder.encode(returnUrl));
        log.info("【微信网页授权】获取code，redirectURL={}", redirectURL);
        return "redirect:" + redirectURL;
    }

    @GetMapping("/qrUserInfo")
    public String qrUserInfo(@RequestParam("code") String code,
                           @RequestParam("state") String returnUrl) {
        log.info("【微信网页授权】code={}", code);
        log.info("【微信网页授权】state={}", returnUrl);
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
        try {
            wxMpOAuth2AccessToken = wxOpenService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            log.error("【微信网页授权】{}", e);
            throw new SellException(ResultEnum.WECHAT_MP_ERROR.getCode(), e.getError().getErrorMsg());
        }

        String openId = wxMpOAuth2AccessToken.getOpenId();
        log.info("【微信网页授权】openId={}", openId);
        return "redirect:" + returnUrl + "?openid=" + openId;
    }

    // 登出


    /**
     * 功能描述: 【买家端】验证微信服务器连接（微信测试账号url,token）
     * <p>
     * 作者: luohongquan
     * 日期: 2018/5/4 0004 9:26
     * @param: [request, response]
     * @return: void
     */
    @GetMapping(value = "portal")
    public void login(HttpServletRequest request, HttpServletResponse response){

        System.out.println("success");
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            if(CheckUtil.checkSignature(signature, timestamp, nonce)){
                out.append(echostr);
                out.flush();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            out.close();
        }
        // 不知道下面没有验证token，但是也可以成功
        /*String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        System.out.println("signature:" + signature);
        System.out.println("timestamp:" + timestamp);
        System.out.println("nonce:" + nonce);
        System.out.println("echostr:" + echostr);
        try {
            PrintWriter pw = response.getWriter();
            pw.append(echostr);
            pw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }*/
    }

    /**
     * 功能描述: 项目首页
     * <p>
     * 作者: luohongquan
     * 日期: 2018/5/3 0003 14:54
     */
    @GetMapping
    public String index() {
        return "index";
    }
}
